﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
using System.IO;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Tasks;

namespace XiaMiRingtone
{
    public partial class setting : PhoneApplicationPage
    {
        public setting()
        {
            InitializeComponent();
            SetSkin();
        }

        private void SetSkin()
        {
            var store = IsolatedStorageFile.GetUserStoreForApplication();
            if (store.FileExists("skin.jpg"))
            {
                using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("skin.jpg", FileMode.Open, store))
                {
                    BitmapImage bi = new BitmapImage();
                    bi.SetSource(stream);
                    Ib.ImageSource = bi;
                }
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            SelectSkin();
        }

        void SelectSkin()
        {
            PhotoChooserTask pc = new PhotoChooserTask();
            pc.Show();
            pc.Completed += new EventHandler<PhotoResult>(pc_completed);
        }

        void pc_completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                var store = IsolatedStorageFile.GetUserStoreForApplication();
                if (store.FileExists("skin.jpg"))
                {
                    store.DeleteFile("skin.jpg");
                }
                IsolatedStorageFileStream fileStream = store.CreateFile("skin.jpg");
                BitmapImage bitmap = new BitmapImage();
                bitmap.SetSource(e.ChosenPhoto);
                WriteableBitmap wb = new WriteableBitmap(bitmap);
                Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);

                fileStream.Close();
                SetSkin();
            }
        }

        
    }
}